<script setup lang="ts">
import { getProcessevalSearchApi } from '@/common/apis/train'
import { ref, onActivated, defineExpose, computed, watch } from 'vue'
import type { TabsPaneContext } from 'element-plus'

interface Props {
  task_id: {
    required: true,
    type: string,
    default: "",
  }
  round_number: string
}
const props = defineProps<Props>()
const emit = defineEmits(['handleClickItem'])

// 所有数据列表
const allList = ref<any[]>([])
const notStartArr = ref<any[]>([])
const inProgressArr = ref<any[]>([])
const finishArr = ref<any[]>([])
const errorArr = ref<any[]>([])

// 各状态数量
const allListNum = ref<number>(0)
const notStartNum = ref<number>(0)
const inProgressNum = ref<number>(0)
const finishNum = ref<number>(0)
const errorNum = ref<number>(0)

// 维护“当前选中的标签”数组（伪 Tab 逻辑保持不变）
const selectedTabs = ref<string[]>(['全部'])
const tabLabels = ['全部', '未开始', '进行中', '报错', '已结束']

// —— 新增：用于“点击后高亮”的选中项 ——
// selectedItem 保存被点击的小方框对应的 item 对象
const selectedItem = ref<any>(null)

// 获取接口并拆分各状态的数组、统计数量
const getProcessevalSearch = async () => {
  const data = { task_id: props.task_id }
  try {
    const res = await getProcessevalSearchApi(data) as any
    const list = Array.isArray(res.data) ? res.data as any[] : []

    // 先深拷贝到 allList
    allList.value = JSON.parse(JSON.stringify(list))
    allListNum.value = allList.value.length

    // 根据 task_round_status 分组
    notStartArr.value = list.filter(item => item.task_round_status === 0)
    inProgressArr.value = list.filter(item => item.task_round_status === 1)
    finishArr.value = list.filter(item => item.task_round_status === 2)
    errorArr.value = list.filter(item => item.task_round_status === 3)

    notStartNum.value = notStartArr.value.length
    inProgressNum.value = inProgressArr.value.length
    finishNum.value = finishArr.value.length
    errorNum.value = errorArr.value.length
  } catch (err) {
    console.error("接口调用失败：", err)
  }
}

defineExpose({ getProcessevalSearch })

onActivated(() => {
  getProcessevalSearch()
})

// 计算属性：根据 selectedTabs 决定 showList 显示哪些项
const showList = computed<any[]>(() => {
  if (selectedTabs.value.includes('全部')) {
    return allList.value
  }
  const result: any[] = []
  if (selectedTabs.value.includes('未开始')) {
    result.push(...notStartArr.value)
  }
  if (selectedTabs.value.includes('进行中')) {
    result.push(...inProgressArr.value)
  }
  if (selectedTabs.value.includes('已结束')) {
    result.push(...finishArr.value)
  }
  if (selectedTabs.value.includes('报错')) {
    result.push(...errorArr.value)
  }
  return result
})

function toggleTab(label: string) {
  if (label === '全部') {
    selectedTabs.value = ['全部']
    return
  }
  if (selectedTabs.value.includes('全部')) {
    selectedTabs.value = []
  }
  const idx = selectedTabs.value.indexOf(label)
  if (idx > -1) {
    selectedTabs.value.splice(idx, 1)
  } else {
    selectedTabs.value.push(label)
  }
  if (selectedTabs.value.length === 0) {
    selectedTabs.value = ['全部']
  }
}

// 原有 tabData，用来显示数量
const tabData = ref<Record<string, string>>({
  "全部": allListNum.value.toString(),
  "未开始": notStartNum.value.toString(),
  "进行中": inProgressNum.value.toString(),
  "报错": errorNum.value.toString(),
  "已结束": finishNum.value.toString(),
})

watch(
  [allListNum, notStartNum, inProgressNum, errorNum, finishNum],
  () => {
    tabData.value = {
      "全部": allListNum.value.toString(),
      "未开始": notStartNum.value.toString(),
      "进行中": inProgressNum.value.toString(),
      "报错": errorNum.value.toString(),
      "已结束": finishNum.value.toString(),
    }
  }
)

// —— 修改：合并点击逻辑 ——
// 点击某个小方框时，先把它设为 selectedItem，再把事件发给父组件
const onClickBox = (item: any) => {
  selectedItem.value = item
  emit('handleClickItem', item)
}
</script>

<template>
  <div class="assessmentInfoTab-container">
    <!-- 伪 Tab 区域（不动） -->
    <div class="tabs-wrapper">
      <div v-for="label in tabLabels" :key="label" class="tab-item" :class="{ selected: selectedTabs.includes(label) }"
        @click="toggleTab(label)">
        <template v-if="label === '全部'">
          全部({{ allListNum }})
        </template>
        <template v-else-if="label === '未开始'">
          <SvgIcon name="notstart" />
          未开始({{ notStartNum }})
        </template>
        <template v-else-if="label === '进行中'">
          <SvgIcon name="inprogress" />
          进行中({{ inProgressNum }})
        </template>
        <template v-else-if="label === '报错'">
          <SvgIcon name="error" />
          报错({{ errorNum }})
        </template>
        <template v-else-if="label === '已结束'">
          <SvgIcon name="finish" />
          已结束({{ finishNum }})
        </template>
      </div>
    </div>

    <!-- 小方框展示区（修改部分） -->
    <div class="img-container">
      <div v-for="item in showList" :key="item.task_process_round + '-' + item.task_round_status" class="img-wrap">
        <!-- 未开始 -->
        <div v-if="item.task_round_status === 0" class="img-container-notstart"
          :class="{ highlighted: selectedItem === item }" @click="onClickBox(item)">
          <div class="title-wrapper">
            <img src="@/common/assets/images/deduct/title-bgc.png" alt="左上角标题背景" class="title-img" />
            <span class="title-text">第{{ item.task_process_round }}局</span>
          </div>
        </div>

        <!-- 进行中 -->
        <div v-else-if="item.task_round_status === 1" class="img-container-inprogress"
          :class="{ highlighted: selectedItem === item }" @click="onClickBox(item)">
          <div class="title-wrapper">
            <img src="@/common/assets/images/deduct/title-bgc.png" alt="左上角标题背景" class="title-img" />
            <span class="title-text">第{{ item.task_process_round }}局</span>
          </div>
        </div>

        <!-- 报错 -->
        <div v-else-if="item.task_round_status === 3" class="img-container-error"
          :class="{ highlighted: selectedItem === item }" @click="onClickBox(item)">
          <div class="title-wrapper">
            <img src="@/common/assets/images/deduct/title-bgc.png" alt="左上角标题背景" class="title-img" />
            <span class="title-text">第{{ item.task_process_round }}局</span>
          </div>
        </div>

        <!-- 已结束 -->
        <div v-else-if="item.task_round_status === 2" class="img-container-finish"
          :class="{ highlighted: selectedItem === item }" @click="onClickBox(item)">
          <div class="title-wrapper">
            <img src="@/common/assets/images/deduct/title-bgc.png" alt="左上角标题背景" class="title-img" />
            <span class="title-text">第{{ item.task_process_round }}局</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped lang="scss">
/* 容器部分保持不变 */

.assessmentInfoTab-container {
  width: 100%;
  padding: 20px;
  margin-bottom: 30px;
  border-radius: 4px;
}

.tabs-wrapper {
  display: flex;
  gap: 20px;
  margin-bottom: 16px;
}

.tab-item {
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  color: #ffffff;
  background-color: transparent;
  transition: color 0.2s;
}

.tab-item.selected {
  color: #02ebc3;
  background-color: transparent;
}

.tab-item:hover {
  color: #02ebc3;
}

/* 图片区布局 */
.img-container {
  margin-top: 12px;
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
  height: auto;
  max-height: 200px;
  overflow-y: auto;
  overflow-x: hidden;
}
.img-container::-webkit-scrollbar {
  width: 8px;
}

.img-container::-webkit-scrollbar-track {
  background-color: transparent;
}

.img-container::-webkit-scrollbar-thumb {
  border-radius: 4px;
  background-color: rgba(144, 147, 153, 0.33);
}

.img-container::-webkit-scrollbar-thumb:hover {
  background-color: rgba(144, 147, 153, 0.47);
}

.img-container::-webkit-scrollbar-thumb:active {
  background-color: rgba(144, 147, 153, 0.60);
}

.img-container::-webkit-scrollbar-corner {
  background-color: transparent;
}
/* 各状态对应小图容器（保持原来的背景图设置） */
.img-container-notstart,
.img-container-inprogress,
.img-container-error,
.img-container-finish {
  position: relative;
  width: 85px;
  height: 85px;
  margin-bottom: 10px;
  opacity: 1;
  /* 默认透明度为 1 */
  transition: opacity 0.2s;
}

/* 未开始 */
.img-container-notstart {
  background: url("@/common/assets/images/deduct/notstart.png") no-repeat center/cover;
}

/* 进行中 */
.img-container-inprogress {
  background: url("@/common/assets/images/deduct/inprogress.png") no-repeat center/cover;
}

/* 报错 */
.img-container-error {
  background: url("@/common/assets/images/deduct/error.png") no-repeat center/cover;
}

/* 已结束 */
.img-container-finish {
  background: url("@/common/assets/images/deduct/finish.png") no-repeat center/cover;
}

/* —— 新增：hover 状态 —— */
.img-container-notstart:hover,
.img-container-inprogress:hover,
.img-container-error:hover,
.img-container-finish:hover {
  opacity: 0.8;
}

/* 左上角标题保持不变 */
.title-wrapper {
  position: absolute;
  top: 1px;
  left: 1px;
  width: 70%;
  height: 20px;
}

.title-wrapper .title-img {
  width: 100%;
  height: 100%;
  display: block;
}

.title-wrapper .title-text {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
  color: #ffffff;
  font-size: 12px;
  white-space: nowrap;
  user-select: none;
}

/* 外层容器，控制布局，无需改动 */
.img-wrap {
  display: flex;
  flex-wrap: wrap;
  cursor: pointer;
  gap: 10px;
}

/* —— 新增：点击后高亮（selected）样式 —— */
.highlighted {
  opacity: 0.8 !important;
}
</style>
